package com.ruoyi.vplat.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.websocket.handler.AbstractWebsocketMsgHandler;
import com.ruoyi.common.websocket.server.WebSocketUtils;
import com.ruoyi.vplat.domain.VplatDevice;
import com.ruoyi.vplat.mapper.VplatDeviceMapper;
import com.ruoyi.vplat.service.IVplatVideoService;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-29
 */
@Service
public class VplatVideoServiceImpl implements IVplatVideoService 
{
    @Autowired
    private VplatDeviceMapper vplatDeviceMapper;

	@Override
	public JSONObject playVideo(Map<String, Object> param) {
		String devId = (String) param.get("devId");
		VplatDevice device = vplatDeviceMapper.selectById(devId);
		if(device == null) {
			return new JSONObject() {{
				put("param", new JSONObject() {{
					put("szDevId", devId);
					put("iMessageCode", -1);
					put("szMessageString", "设备不存在");
				}});
			}};
		}
		String accessType = device.getProtocol();
		String gatewayId = device.getGatewayId();
		String clientId = (String) param.get("clientId");
		String clientType = (String) param.get("protocol");
		Integer videoFlag = (Integer) param.get("videoFlag");
		String seqNum = (String) param.get("seqNum");
		if(StringUtils.isBlank(seqNum)) {
			seqNum = AbstractWebsocketMsgHandler.getRandomNum(7);
		}
		int num = Integer.parseInt(seqNum.toString());
		JSONObject commandTemplate = AbstractWebsocketMsgHandler.getCommandTemplate("2105", new HashMap<String, Object>(){{
			put("protocol", StringUtils.isBlank(clientType) ? 0 : clientType);
			put("seqNum", num);
			put("clientId", clientId);
			put("devId", devId);
			put("videoFlag", videoFlag != null ? videoFlag : 1);
		}});
		String gateway = null;
		if(accessType.equals("2")) {
			gateway = "GB-" + gatewayId;
		}else {
			gateway = "ACS-" + gatewayId;
		}
		JSONObject result = WebSocketUtils.sendSyncMessage(gateway, commandTemplate);
		return result;
	}
    
}
